<template>
  <el-card class="list-card">
    <template #header>
      <div class="card-header">
        <div class="header-left">
          <span class="group-name">{{ groupInfo.groupName || '加载中...' }}</span>
          <el-divider direction="vertical" />
          <span>可选学生列表</span>
        </div>
        <div class="header-right">
          <el-tag type="info" size="small">队伍人数上限: {{ groupInfo.teamMax || '-' }}人</el-tag>
        </div>
      </div>
    </template>

    <div class="card-body">
      <!-- 筛选表单 -->
      <el-form :inline="true" :model="queryParams" class="search-container" style="margin-bottom: 0">
        <el-form-item label="学号">
          <el-input v-model="queryParams.stuId" placeholder="请输入学号" clearable style="width: 180px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="queryParams.nickName" placeholder="请输入姓名" clearable style="width: 180px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="是否已组队">
          <el-select v-model="queryParams.isTeam" placeholder="请选择" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="未组队" :value="false" />
            <el-option label="已组队" :value="true" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 学生列表 -->
      <div class="table-container">
        <el-table v-loading="loading" :data="studentList" border row-key="studentId" height="100%">
          <el-table-column label="学号" align="center" prop="stuId" />
          <el-table-column label="姓名" align="center" prop="user.nickName" />
          <el-table-column label="专业" align="center" prop="major.majorName" show-overflow-tooltip />
          <el-table-column label="组队状态" prop="isTeam" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.studentTeam !== null ? 'success' : 'info'" size="small">
                {{ row.studentTeam == null ? '未组队' : '已组队' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="邮箱" align="center" prop="email" />
          <el-table-column label="个人简介" align="center">
            <template #default="{ row }">
              <span style="cursor: pointer; color: var(--el-color-primary)" @click="handleView(row)">查看</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right">
            <template #default="{ row }">
              <el-button v-if="!isSelected(row.studentId)" link type="primary" size="small" @click="handleSelect(row)" :disabled="row.studentTeam !== null">选择</el-button>
              <el-button v-else link type="danger" size="small" @click="handleUnselect(row.studentId)">取消</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :page-sizes="[30, 50, 100]" @pagination="getStudentList" />
    </div>
  </el-card>
</template>

<script setup>
import { ref, getCurrentInstance, watch } from 'vue'
import { getInfo } from '@/api/group'

const props = defineProps({
  groupId: {
    type: String,
    required: true
  },
  groupInfo: {
    type: Object,
    default: () => ({})
  },
  selectedStudents: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['select-student', 'unselect-student', 'view-student', 'refresh-completed'])

const { proxy } = getCurrentInstance()

// 学生列表相关
const loading = ref(false)
const studentList = ref([])
const total = ref(0)
const queryParams = ref({
  pageNum: 1,
  pageSize: 30,
  stuId: '',
  nickName: '',
  isTeam: ''
})

// 获取学生列表
const getStudentList = async () => {
  if (!props.groupId) {
    proxy.$modal.msgError('缺少分组信息')
    return
  }

  loading.value = true
  try {
    const res = await getInfo(props.groupId, queryParams.value)
    if (res && res.data) {
      studentList.value = res.data.rows || []
      total.value = res.data.total || 0
    }
  } catch (error) {
    console.error('获取学生列表失败:', error)
    proxy.$modal.msgError('获取学生列表失败')
  } finally {
    loading.value = false
    emit('refresh-completed')
  }
}

// 搜索
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getStudentList()
}

// 重置搜索
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 30,
    stuId: '',
    nickName: '',
    isTeam: ''
  }
  getStudentList()
}

// 判断是否已选
const isSelected = (studentId) => {
  return props.selectedStudents.some((s) => s.studentId === studentId)
}

// 选择学生
const handleSelect = (student) => {
  emit('select-student', student)
}

// 取消选择学生
const handleUnselect = (studentId) => {
  emit('unselect-student', studentId)
}

// 查看学生详情
const handleView = (row) => {
  emit('view-student', row)
}

// 刷新列表（暴露给父组件）
const refresh = () => {
  getStudentList()
}

// 监听 groupId 变化
watch(
  () => props.groupId,
  (newVal) => {
    if (newVal) {
      getStudentList()
    }
  },
  { immediate: true }
)

// 暴露方法给父组件
defineExpose({
  refresh
})
</script>

<style scoped>
.list-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.list-card :deep(.el-card__body) {
  flex: 1;
  overflow: hidden;
  padding: 0;
  display: flex;
  flex-direction: column;
}

.card-body {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  flex-shrink: 0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 24px;
}

.group-name {
  color: var(--el-color-primary);
  font-weight: 600;
}

.header-right {
  display: flex;
  align-items: center;
}

.table-container {
  flex: 1;
  overflow: hidden;
  min-height: 0;
}

.table-container :deep(.el-table) {
  height: 100%;
}

.table-container :deep(.el-table__body-wrapper) {
  overflow-y: auto;
}
</style>
